package com.kk.mybatis.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.kk.mybatis.entity.Label;
import com.kk.mybatis.entity.vo.LabelVO;
import com.kk.mybatis.mapper.LabelMapper;
import com.kk.mybatis.service.LabelService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description:
 * @author: Kk
 * @create: 2020-11-27 19:39
 **/
@Service
public class LabelServiceImpl implements LabelService {

    @Resource
    private LabelMapper labelMapper;

    //递归查找
    @Override
    public LabelVO buildLabelByLabelId(int labelId) {
        //查看该标签是否存在
        Label label = labelMapper.selectByPrimaryKey(labelId);
        Assert.notNull(label,"标签不存在");

        LabelVO labelVO = new LabelVO();
        BeanUtil.copyProperties(label,labelVO);
        List<LabelVO> children = labelMapper.selectLabelChildren(labelId);
        if (children==null || children.size()==0){
            labelVO.setLeaf(true);
        }
        labelVO.setChildren(buildLabel(children));
        return labelVO;
    }

    @Override
    public void save(Label label) {
        labelMapper.insert(label);
    }

    @Override
    public boolean removeById(int id) {
        //更改为逻辑删除
        //int index = labelMapper.deleteByPrimaryKey(id);
        int index = labelMapper.logicDelete(id);
        return index==0?false:true;
    }

    //递归
    private List<LabelVO> buildLabel(List<LabelVO> children) {
        for (LabelVO labelVO:children){
            //优化查询数量即可
            int count = labelMapper.countById(labelVO.getId());
            if (count==0){
                labelVO.setLeaf(true);
            }else{
                List<LabelVO> son = labelMapper.selectLabelChildren(labelVO.getId());
                labelVO.setChildren(buildLabel(son));
            }
        }
        return children;
    }
}
